﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace _14_缓存.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class 缓存穿透Controller : ControllerBase
    {
        private readonly IMemoryCache memoryCache;
        public 缓存穿透Controller(IMemoryCache memoryCache)
        { 
            this.memoryCache = memoryCache;
        }
        [HttpGet]
        public async Task<ActionResult<Book?>> SetAndGetCatch(int id)
        {
            Console.WriteLine("------------------------");
            // 如果数据库中没有响应的id的书，如果恶意不断访问，则缓存都是null，导致大量无效访问数据库  =》这叫缓存穿透
            // 所以不推荐使用
            string cacheKey = "Book" + id;
            Book? b = memoryCache.Get<Book?>(cacheKey); // 获取缓存
            if (b == null)
            {
                Console.WriteLine("查询数据....");
                b=await MyDbContext.GetByIdAsync(id);
                memoryCache.Set(cacheKey, b); // 设置缓存
            }
            return b;
        }
    }
}
